在專案中,我們常常需要重複使用某些資料處理邏輯,例如:
可以將自訂函式放在 app/Helpers/Helper.php:
<?php
if (! function_exists('wrapArrayIfNotList')) {
function wrapArrayIfNotList($data): array
{
if (is_null($data)) {
return [];
}
return array_is_list($data) ? $data : [$data];
}
}
修改 composer.json,加入以下設定:
"autoload": {
"files": [
"app/Helpers/Helper.php"
]
}
composer dump-autoload
執行完後,Helper 函式就能在整個專案中直接使用!
$data = ['name' => 'Harry'];
$arrayData = wrapArrayIfNotList($data);